import Cesium from "../Ces/Cesium"
import WeDisplay from "./WeDisplay"
import WeDisplayEffectNumber from "./WeDisplayEffectNumber"
import WeSurface from "./WeSurface"

class WeGridValue {
  private display: WeDisplay
  private primitive: WeSurface
  private displayEffectNumber: WeDisplayEffectNumber
  private currentLod: number = 0
  private dirty = false
  repeatFactor: number
  startLod: number
  endLod: number
  constructor(options) {
    this.display = options.display

    this.repeatFactor = options?.repeatFactor?? 16
    this.startLod = options?.startLod?? 0
    this.endLod = options?.endLod?? 12

    this.dirty = true
  }

  rebuild(frameState) {
    this.primitive = this.primitive?.destroy()
    this.displayEffectNumber = this.displayEffectNumber?.destroy()

    this.displayEffectNumber = new WeDisplayEffectNumber(frameState)
    this.primitive = new WeSurface({
      clampToGround: false,
      useGridEffect: true,
      display: this.display,
      effect: this.displayEffectNumber
    })
  }

  update(frameState) {
    if (!frameState.passes.render
    ) return

    if (this.dirty) {
      this.dirty = false
      this.rebuild(frameState)
    }


    const scaleListener = frameState.scaleListener
    if (this.currentLod !== scaleListener.currentLod) {
      let repeatFactor = this.repeatFactor

      const currentLod = scaleListener.currentLod
      const startLod = this.startLod
      const endLod = this.endLod
      if (currentLod < startLod) {
        let n = startLod - currentLod
        let m = 1
        if (currentLod < endLod) {
          n = startLod - endLod
          m = endLod - currentLod
        }
        repeatFactor *= Math.pow(0.5, n)
      }

      this.displayEffectNumber.repeatFactor = Cesium.Math.clamp(repeatFactor, 1, repeatFactor)
      this.currentLod = currentLod
    }

    this.primitive?.update(frameState)
  }

  isDestroyed() { return false }
  destroy() {
    this.displayEffectNumber = this.displayEffectNumber?.destroy()
    return Cesium.destroyObject(this)
  }
}

export default WeGridValue
